package parkshop.pmcourse.controller;


import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import parkshop.pmcourse.domain.Advertisement;
import parkshop.pmcourse.domain.Product;
import parkshop.pmcourse.domain.Shop;
import parkshop.pmcourse.dto.PageBean;
import parkshop.pmcourse.dto.User;
import parkshop.pmcourse.service.AdvertisementService;
import parkshop.pmcourse.service.CustomerService;
import parkshop.pmcourse.service.MallAdministratorService;
import parkshop.pmcourse.service.ProductService;
import parkshop.pmcourse.service.ShopOwnerService;
import parkshop.pmcourse.service.ShopService;
import parkshop.pmcourse.utils.ConstantUtil;
import parkshop.pmcourse.utils.SendMailThread;

@Controller
public class ParkShopCtrl {
	
	private static final Logger logger = LoggerFactory.getLogger(ParkShopCtrl.class);
	
	@Autowired
	private ProductService productService;
	

	@Autowired
	private MallAdministratorService mallAdministratorService;
	@Autowired
	private ShopOwnerService shopOwnerService;
	@Autowired
	private CustomerService customerService;
	
	@Autowired
	private AdvertisementService advertisementService;
	@Autowired
	private ShopService shopService;
	
	@RequestMapping("/")
	public String welcome(Model model,HttpSession httpSession){
		//   "/" 映射到管理员的商店
		List<Advertisement> ADList=advertisementService.getAdvertisementsByShopId((long) ConstantUtil.adminShopMark);
		model.addAttribute("ADList", ADList);
		
		//List<Product> productList = productService.getTopProductsByAdmin();// -1 表示查询所有商店的
		PageBean pageBean=productService.getProductsByPage(1, ConstantUtil.adminShopMark);
		model.addAttribute("productPage", pageBean);
		return "index";
	}

	@RequestMapping("/type/{shopId}/{type}")
	public String getOneKindTypeProduct(@PathVariable Long shopId,@PathVariable String type,Model model,HttpSession httpSession){
		//   "/" 映射到管理员的商店
		List<Advertisement> ADList=advertisementService.getAdvertisementsByShopId((long) ConstantUtil.adminShopMark);
		model.addAttribute("ADList", ADList);
		
		PageBean productList = productService.getProductsByType(1, type, shopId);
		model.addAttribute("productPage", productList);
		return "index";
	}
	
	@GetMapping("/signin")
	public String signIn() {
		/*
		 * go to signin page
		 */
		return "signin";
	}
	@GetMapping("/signup")
	public String signUp() {
		/*
		 * if customer then goods page if seller then shop page if manager then
		 * manager page
		 */
		return "signup";
	}
	@GetMapping("/logout/{userType}")
	public String logout(@PathVariable String userType,HttpServletRequest request, Model model) {

		HttpSession session=request.getSession(false);
		if(session!=null){
			session.removeAttribute(ConstantUtil.nameOfCurUser);
		}
		model.addAttribute("userType", userType);//跳转到该角色的登陆页面
		return "signin";
	}
	
	/*
	 * administrator sign in && sign up
	 */
			@PostMapping("/signin")
			public String doSignin(User user,HttpServletRequest request, Model model){

				User curUser=null;
				String successUrl="module/personInfo";
				switch(user.getType()){
				case ConstantUtil.userTypeAdministrator:
					curUser=mallAdministratorService.signin(user.getName(), user.getPassword());					
					break;
				case ConstantUtil.userTypeShopOwner:
					curUser=shopOwnerService.signin(user.getName(), user.getPassword());
					successUrl="redirect:/shopOwner/products/list/1";
					break;
				case ConstantUtil.userTypeCustomer:
					curUser=customerService.signin(user.getName(), user.getPassword());
					break;
				}
				if(curUser!=null){
					HttpSession session=request.getSession();
					session.setAttribute(ConstantUtil.nameOfCurUser, curUser);
					model.addAttribute(ConstantUtil.nameOfCurUser, curUser);
					return successUrl;
				}

				model.addAttribute("message", "account was not exist or not in active");
				return "signin";				
			
			}
			@PostMapping("/signup")
			public String doSignup(String shopName,User user,HttpServletRequest request, Model model){
				
				boolean flag=false;
				
				//发邮件
				String activeCode = UUID.randomUUID().toString();
				user.setActiveCode(activeCode);
				user.setIsActived((byte)0);
				new SendMailThread(user,request.getServerName(),request.getServerPort()).start();
				
				switch(user.getType()){
				case ConstantUtil.userTypeAdministrator:
					flag=mallAdministratorService.signup(user);
					break;
				case ConstantUtil.userTypeShopOwner:
					flag=shopOwnerService.signup(user,shopName);
					break;
				case ConstantUtil.userTypeCustomer:
					flag=customerService.signup(user);
					break;
				}
				if(flag)
					return "activeCode";
				else
					return "signup";				
				
			}
			
			@GetMapping("/activeUser/{userType}")
			public String activeUser(@PathVariable String userType,String code,HttpServletRequest request, Model model){
				
				boolean flag=false;
				
				switch(userType){
				case ConstantUtil.userTypeAdministrator:
					flag=mallAdministratorService.activeUser(code);
					break;
				case ConstantUtil.userTypeShopOwner:
					flag=shopOwnerService.activeUser(code);
					break;
				case ConstantUtil.userTypeCustomer:
					flag=customerService.activeUser(code);
					break;
				}
				if(flag){
					model.addAttribute("message", "your account was actived successful");
					return "signin";
				}else
					return "signup";				
				
			}
			
			/*
			 * 访问店铺的入口。 管理员的店铺id，默认为  ConstantUtil.adminShopMark
			 */
			@GetMapping("/shop/{shopId}/{pageNumber}")
			public String viewShop(@PathVariable Long shopId,@PathVariable int pageNumber,HttpSession httpSession, Model model){
				
				List<Advertisement> ADList=advertisementService.getAdvertisementsByShopId((long) shopId);
				model.addAttribute("ADList", ADList);
				
				PageBean pageBean = productService.getProductsByPage(pageNumber, (long) shopId);
				model.addAttribute("productPage", pageBean);
				
				Shop shop=shopService.getShopById(shopId);
				model.addAttribute("shop", shop);
				return "index";
			}
			@PostMapping("/user/info/get")
			public void getUserInfo(HttpServletRequest request,HttpServletResponse response) throws IOException{
			HttpSession session=request.getSession(false);
			if(session==null){
					response.getWriter().write("please signin first");
					return;
			}
			User user=(User) session.getAttribute(ConstantUtil.nameOfCurUser);
			
			if(user!=null&&!ConstantUtil.userTypeCustomer.equals(user.getType())){
				response.getWriter().write("please signin as a customer");
				return;
				}
			response.getWriter().write("customer");
			}

		
}
